#!/bin/bash

echo "=========================================="
echo "  启动所有微服务"
echo "=========================================="
echo ""

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# 项目根目录（假设脚本在 resources/scripts/ 目录下）
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

echo "📂 项目根目录: $PROJECT_ROOT"
echo ""

# 编译项目
echo "🔨 编译项目..."
cd "$PROJECT_ROOT"
mvn clean install -Dmaven.test.skip=true -q
echo "✅ 编译完成"
echo ""

# 启动 Order Service
echo "🚀 启动 Order Service (8001)..."
cd "$PROJECT_ROOT/services/order-service"
nohup mvn spring-boot:run > /tmp/order-service.log 2>&1 &
ORDER_PID=$!
echo "   PID: $ORDER_PID"
echo ""

# 启动 Storage Service
echo "🚀 启动 Storage Service (8002)..."
cd "$PROJECT_ROOT/services/storage-service"
nohup mvn spring-boot:run > /tmp/storage-service.log 2>&1 &
STORAGE_PID=$!
echo "   PID: $STORAGE_PID"
echo ""

# 启动 Account Service
echo "🚀 启动 Account Service (8003)..."
cd "$PROJECT_ROOT/services/account-service"
nohup mvn spring-boot:run > /tmp/account-service.log 2>&1 &
ACCOUNT_PID=$!
echo "   PID: $ACCOUNT_PID"
echo ""

echo "⏳ 等待服务启动（约60秒）..."

# 等待服务启动
for i in {1..20}; do
    sleep 5
    echo -n "."

    ORDER_UP=$(nc -z localhost 8001 2>/dev/null && echo "1" || echo "0")
    STORAGE_UP=$(nc -z localhost 8002 2>/dev/null && echo "1" || echo "0")
    ACCOUNT_UP=$(nc -z localhost 8003 2>/dev/null && echo "1" || echo "0")

    if [[ "$ORDER_UP" == "1" && "$STORAGE_UP" == "1" && "$ACCOUNT_UP" == "1" ]]; then
        echo ""
        echo ""
        echo "=========================================="
        echo "  ✅ 所有服务启动成功！"
        echo "=========================================="
        echo ""
        echo "服务地址："
        echo "  - Order Service:   http://localhost:8001"
        echo "  - Storage Service: http://localhost:8002"
        echo "  - Account Service: http://localhost:8003"
        echo ""
        echo "健康检查："
        curl -s http://localhost:8001/order/health
        echo ""
        curl -s http://localhost:8002/storage/health
        echo ""
        curl -s http://localhost:8003/account/health
        echo ""
        exit 0
    fi
done

echo ""
echo "⚠️  服务启动超时，请查看日志："
echo "  tail -f /tmp/order-service.log"
echo "  tail -f /tmp/storage-service.log"
echo "  tail -f /tmp/account-service.log"
